package org.example.domain.order.service.mq_v1;


import cn.hutool.json.JSONUtil;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.example.domain.order.adapter.repository.IOrderRepository;
import org.example.domain.order.model.entity.OrderEntity;
import org.example.types.enums.ResponseCode;
import org.example.types.exception.AppException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

import static org.example.types.common.MQConstants.*;

/**
 * @author yinghuashen
 * @version 1.0
 * @description:
 * @date 2025/3/9 23:46
 */

@Service
@RocketMQMessageListener(consumerGroup = LOCK_ORDER_CONSUMER_GROUP,
        topic = LOCK_ORDER_TOPIC,
        selectorExpression = NEW_ORDER_TAG,
        messageModel = MessageModel.CLUSTERING
)
public class LockOrderConsumer implements RocketMQListener<MessageExt> {

    @Resource
    private IOrderRepository orderRepository;

    @Override
    public void onMessage(MessageExt messageExt) {
        if(messageExt.getBody()==null){
            return;
        }
        try {
            OrderEntity orderEntity = JSONUtil.toBean(new String(messageExt.getBody(), StandardCharsets.UTF_8), OrderEntity.class);

            // 检查订单是否已经存在
            boolean orderExists = orderRepository.checkOrderExists(orderEntity.getOrderId());
            if (orderExists) {
                // 订单已存在，直接返回，避免重复处理
                return;
            }

            boolean saveOrder = orderRepository.saveOrder(orderEntity);
            if(!saveOrder){
                throw new AppException(ResponseCode.ORDER_DB_INSERT_ERROR);
            }
        } catch (Exception e){
            throw new AppException(ResponseCode.ORDER_DB_INSERT_ERROR);
        }
    }
}
